package cn.fl.capital.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapFundVfDtlQueryCondition;
import cn.fl.capital.condition.CapFundVfLogQueryCondition;
import cn.fl.capital.condition.CapOverdueInfoQueryCondition;
import cn.fl.capital.constant.CapPayInfoConstant;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.capital.dto.CapFundVfDtlDTO;
import cn.fl.capital.dto.CapOverdueInfoDTO;
import cn.fl.capital.service.ICapFundVfDtlApiService;
import cn.fl.capital.service.ICapFundVfDtlService;
import cn.fl.capital.service.ICapOverdueInfoApiService;
import cn.fl.capital.transform.CapFundVfDtlVOTransform;
import cn.fl.capital.vo.CapFundVfDtlVO;
import cn.fl.flow.service.IFlowService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.condition.PrjPrdPaySchDQueryCondition;
import cn.fl.project.constant.PrjPrdPaySchDConstant;
import cn.fl.project.dto.PrjPrdPaySchDDTO;
import cn.fl.project.service.IPrjPrdPaySchDApiService;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;

/**
 * @Description: 客户资金核销记录表 客户端服务层接口实现
 * 业务层方法名称前缀：
 * 新增：add*
 * 删除：remove*
 * 修改：modify*
 * 批量：batch*
 * 查询对象：select* get*
 * 查询集合：search*
 */
@Service
public class CapFundVfDtlServiceImpl implements ICapFundVfDtlService {

	/**
     * 日志
     */
    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(CapFundVfDtlServiceImpl.class);
	
	/**
	 * CapFundVfDtl API 暴露服务
	 */
	@Autowired
	private ICapFundVfDtlApiService capFundVfDtlApiService;
    @Autowired
    private IPrjPrdPaySchDApiService prjPrdPaySchDApiService;
    @Autowired
    private ICapOverdueInfoApiService capOverdueInfoApiService;
	/**
     * 数据字典服务
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
    
    /**
     * 流程本地服务
     */
    @Autowired
	private IFlowService flowService;

	@Override
	public CapFundVfDtlVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)) return null;
		CapFundVfDtlDTO dto = this.capFundVfDtlApiService.selectCapFundVerificationById(id);
		return CapFundVfDtlVOTransform.toVO(dto);
	}

	@Override
	public Long add(CapFundVfDtlVO entity) throws BaseException{
		if(null == entity) return null;
		return this.capFundVfDtlApiService.addCapFundVerification(CapFundVfDtlVOTransform.toDTO(entity));
	}

	@Override
	public boolean removeByIds(List<Long> ids) throws BaseException{
		if(CollectionUtils.isEmpty(ids)) return false;
		return this.capFundVfDtlApiService.removeCapFundVerificationByIds(ids,CurrentThreadContext.getCurrentUserId());
	}

	@Override
	public boolean modify(CapFundVfDtlVO entity) throws BaseException{
		if(null == entity) return false;
		return this.capFundVfDtlApiService.modifyCapFundVerification(CapFundVfDtlVOTransform.toDTO(entity));
	}

	@Override
	@SuppressWarnings("unchecked")
	public Pager searchListPage(Pager page) throws BaseException{
        CapFundVfDtlQueryCondition condition=null;
        if(null == page) {
            page = new Pager();
            page.setCondition(new CapFundVfDtlQueryCondition());
        }
		condition=(CapFundVfDtlQueryCondition)page.getCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
		page=this.capFundVfDtlApiService.searchCapFundVerificationListPage(page);
		
		if(CollectionUtils.isNotEmpty(page.getResultList())){
          
			List<CapFundVfDtlVO> voList= CapFundVfDtlVOTransform.toVOList((List<CapFundVfDtlDTO>)page.getResultList());
            this.setDicDescomtData(voList);
            page.setResultList(voList);
        }
        return page;
	}
	
	@Override
	public List<CapFundVfDtlVO> searchList(CapFundVfDtlQueryCondition condition) throws BaseException{
		if(null == condition) condition=new CapFundVfDtlQueryCondition();
		condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
		condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
		condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
		List<CapFundVfDtlVO> voList= CapFundVfDtlVOTransform.toVOList(this.capFundVfDtlApiService.searchCapFundVerificationList(condition));
		this.setDictData(voList);
		return voList;
	}

    /*******************************
     * 根据条件查询所有资金分解明细
     * @param condition
     * @return
     *******************************/
    @Override
    public List<CapFundVfDtlVO> searchDecomDtlList(CapFundVfDtlQueryCondition condition) throws BaseException {
        List<CapFundVfDtlDTO> vfDtlDTOList=this.capFundVfDtlApiService.searchCapFundVerificationList(condition);
        if(CollectionUtils.isNotEmpty(vfDtlDTOList)){
            List<CapFundVfDtlVO> voList=CapFundVfDtlVOTransform.toVOList(vfDtlDTOList);
            List<Long> payDetailIds=new ArrayList<>();//支付表明细ID集合
            List<Long> ovdIds=new ArrayList<>();//罚息明细ID集合
            for(CapFundVfDtlVO vfDtlVO:voList){
                if(CapitalConstant.CODE_FEE_TYP_CD_S05.equals(vfDtlVO.getFeeTypCd())){
                    if(!ovdIds.contains(vfDtlVO.getPayDetailId())){
                        ovdIds.add(vfDtlVO.getPayDetailId());
                    }
                }else{
                    if(!payDetailIds.contains(vfDtlVO.getPayDetailId())){
                        payDetailIds.add(vfDtlVO.getPayDetailId());
                    }
                }
            }

            Map<Long,PrjPrdPaySchDDTO> schDDTOMap=null;//支付表集合
            Map<Long,CapOverdueInfoDTO> overdueInfoDTOMap=null;//逾期罚息集合
            if(CollectionUtils.isNotEmpty(payDetailIds)){
                PrjPrdPaySchDQueryCondition schDQueryCondition=new PrjPrdPaySchDQueryCondition();
                schDQueryCondition.setIdList(payDetailIds);
                List<PrjPrdPaySchDDTO> schDDTOList=this.prjPrdPaySchDApiService.searchPrjPrdPaySchDList(schDQueryCondition);
                if(CollectionUtils.isNotEmpty(schDDTOList)){
                    schDDTOMap=new HashMap<>(schDDTOList.size());
                    for(PrjPrdPaySchDDTO schDDTO:schDDTOList){
                        schDDTOMap.put(schDDTO.getId(),schDDTO);
                    }
                }
            }
            if(CollectionUtils.isNotEmpty(ovdIds)){
                CapOverdueInfoQueryCondition overdueInfoQueryCondition=new CapOverdueInfoQueryCondition();
                overdueInfoQueryCondition.setIdList(ovdIds);
                List<CapOverdueInfoDTO> overdueInfoDTOList=this.capOverdueInfoApiService.searchCapOverdueInfoList(overdueInfoQueryCondition);
                overdueInfoDTOMap=new HashMap<>(overdueInfoDTOList.size());
                for(CapOverdueInfoDTO overdueInfoDTO:overdueInfoDTOList){
                    overdueInfoDTOMap.put(overdueInfoDTO.getId(),overdueInfoDTO);
                }
            }

            //费用类型
            Map<String,String> feeTypCdMap=this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(),
                    CurrentThreadContext.getCurrentOrgCd(), PrjPrdPaySchDConstant.CODE_FEE_TYP_CD);
            Map<String,String> vfStsCdMap=this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(),
                    CurrentThreadContext.getCurrentOrgCd(),CapitalConstant.CODE_CAP_FUND_STS_CD);
            for(CapFundVfDtlVO vfDtlVO:voList){
                if(CapitalConstant.CODE_FEE_TYP_CD_S05.equals(vfDtlVO.getFeeTypCd())){
                    if(overdueInfoDTOMap.containsKey(vfDtlVO.getPayDetailId())){
                        CapOverdueInfoDTO overdueInfoDTO=overdueInfoDTOMap.get(vfDtlVO.getPayDetailId());
                        vfDtlVO.setPayDt(overdueInfoDTO.getCreateDate());//罚息日期
                        vfDtlVO.setPayFeeAmt(overdueInfoDTO.getPenaltyAmount());
                    }
                }else{
                    if(schDDTOMap.containsKey(vfDtlVO.getPayDetailId())){
                        PrjPrdPaySchDDTO paySchDDTO=schDDTOMap.get(vfDtlVO.getPayDetailId());
                        vfDtlVO.setPayDt(paySchDDTO.getPayDt());
                        vfDtlVO.setPayFeeAmt(paySchDDTO.getFeeAmt().longValue());
                    }
                }
                if(feeTypCdMap!=null&&feeTypCdMap.containsKey(vfDtlVO.getFeeTypCd())){
                    if (vfDtlVO.getPayPd()==0l){
                        vfDtlVO.setFeeTypCdNm(feeTypCdMap.get(vfDtlVO.getFeeTypCd()));
                    }else{
                        vfDtlVO.setFeeTypCdNm("第"+vfDtlVO.getPayPd()+"期"+feeTypCdMap.get(vfDtlVO.getFeeTypCd()));
                    }
                }
                if(vfStsCdMap!=null&&vfStsCdMap.containsKey(vfDtlVO.getVfStsCd())){
                    vfDtlVO.setVfStsCdNm(vfStsCdMap.get(vfDtlVO.getVfStsCd()));
                }
            }
            return voList;
        }
        return null;
    }

    /*******************************
     * 冲红申请
     * @param condition
     * @return
     * @throws BaseException
     *******************************/
    @Override
    public DataResultVO modifyFundRevert(CapFundVfDtlQueryCondition condition) throws BaseException {
        DataResultDTO result=this.capFundVfDtlApiService.modifyFundRevert(condition,getFlowStartParams(FlowConstant.FLOW_BUSINESS_TYP_RUSH_RED,FlowConstant.FLOW_MODEL_TYP_RUSH_RED_1));
        if(null!=result){
            DataResultVO resultVO=new DataResultVO(Integer.valueOf(result.getCode()),result.getInfo());
            resultVO.setData(result.getData());
            return resultVO;
        }else{
            return new DataResultVO(BaseConstant.IS_YESNO_NO,"冲红申请流程发起失败");
        }
    }

    /*******************************
     * 减免罚息申请，发起减免流程
     * @param condition
     * @return
     * @throws BaseException
     *******************************/
    @Override
    public DataResultVO modifyFineReduction(CapFundVfDtlQueryCondition condition) throws BaseException {
        if(StringUtils.isNotEmpty(condition.getVfId())){
            DataResultDTO result=this.capFundVfDtlApiService.modifyFineReduction(condition);
            if(null!=result){
                return new DataResultVO(Integer.valueOf(result.getCode()),result.getInfo());
            }else{
                return new DataResultVO(BaseConstant.IS_YESNO_NO,"修改失败");
            }
        }else{
            DataResultDTO result=this.capFundVfDtlApiService.modifyFineReduction(condition,getFlowStartParams(FlowConstant.FLOW_BUSINESS_TYP_REDUCE,FlowConstant.FLOW_MODEL_TYP_REDUCE));
            if(null!=result){
                DataResultVO resultVO=new DataResultVO(Integer.valueOf(result.getCode()),result.getInfo());
                resultVO.setData(result.getData());
                return resultVO;
            }else{
                return new DataResultVO(BaseConstant.IS_YESNO_NO,"减免罚息申请流程发起失败");
            }
        }
    }

    /**
     * 获取发起流程对象
     * @param businessType:业务类型
     * @param modelTyp:流程业务分类
     * @return
     * @throws BaseException
     */
    private FlowStartParamsDTO getFlowStartParams(String businessType,String modelTyp)throws BaseException{
    	if(StringUtils.isEmpty(modelTyp)){
    		throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "流程业务分类不能为空");
    	}
        FlowStartParamsDTO flowStartParamsDTO = new FlowStartParamsDTO();
        //流程定义KEY和流程定义ID不定义  流程发起的时候会根据模块类型查找唯一流程去发起
        //flowStartParamsDTO.setProcDefKey("");
        //flowStartParamsDTO.setProcDefId("");
        flowStartParamsDTO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);
        flowStartParamsDTO.setWordsInTheTable(CapPayInfoConstant.CAP_FLOW_S_H_CAP);
        flowStartParamsDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
        flowStartParamsDTO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
        flowStartParamsDTO.setSysCd(CurrentThreadContext.getCurrentSysCd());
        flowStartParamsDTO.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
        flowStartParamsDTO.setInitiator(String.valueOf(CurrentThreadContext.getCurrentUserId()));
        flowStartParamsDTO.setInitiatorNm(CurrentThreadContext.getCurrentUserName());
        flowStartParamsDTO.setProcPriority(FlowConstant.FLOW_PRIORITY_EMERGENCY);//优先级,可以在界面定义
        flowStartParamsDTO.setBusinessType(businessType);//TODO 确认用不用
        flowStartParamsDTO.setModelTyp(modelTyp);//需要和流程配置中的模块类型匹配
        //flowStartParamsDTO.setSearchDesc(CurrentThreadContext.getCurrentOrgDispNm()+"、承租人、项目名称、查询大字段名称");
        return flowStartParamsDTO;
    }

    /**
     * 添加数据字典名称
     * @param voList
     */
	public void setDictData(List<CapFundVfDtlVO> voList){
		if(CollectionUtils.isEmpty(voList)) return;
		Map<String, String> feeTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapitalConstant.CODE_VF_FEE_TYP_CD);
        Map<String, String> vfStsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapitalConstant.CODE_CAP_FUND_STS_CD);
		for(CapFundVfDtlVO vo:voList){
			if (feeTypCdMap != null && feeTypCdMap.containsKey(vo.getFeeTypCd())) {
			    if(vo.getPayPd()>0){
			        if(CapitalConstant.CODE_FEE_TYP_CD_S05.equals(vo.getFeeTypCd())){
                        vo.setFeeTypCdNm(feeTypCdMap.get(vo.getFeeTypCd()));
                        vo.setPayDt(null);
                    }else{
                        vo.setFeeTypCdNm("第"+vo.getPayPd()+"期"+feeTypCdMap.get(vo.getFeeTypCd()));
                    }
                }else{
                    vo.setFeeTypCdNm(feeTypCdMap.get(vo.getFeeTypCd()));
                }
        	}
            if (vfStsCdMap != null && vfStsCdMap.containsKey(vo.getVfStsCd())) {
                vo.setVfStsCdNm(vfStsCdMap.get(vo.getVfStsCd()));
            }
		}
	}
	
	 /**
     * 添加数据字典名称
     * @param voList
     */
	public void setDicDescomtData(List<CapFundVfDtlVO> voList){
		if(CollectionUtils.isEmpty(voList)) return;
		//核销类型
		Map<String, String> feeTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapitalConstant.CODE_CAP_VF_TYP_CD);
		// 资金状态集合 CAP0004：0.未分解1.分解中2.已分解3.已作废4.冲红中5.已冲红6.已转出 7.减免中 8.已减免
        Map<String, String> vfStsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapitalConstant.CODE_CAP_FUND_STS_CD);
        
		for(CapFundVfDtlVO vo:voList){
            if (vfStsCdMap != null && vfStsCdMap.containsKey(vo.getVfStsCd())) {
                vo.setVfStsCdNm(vfStsCdMap.get(vo.getVfStsCd()));
            }
            if (feeTypCdMap != null && feeTypCdMap.containsKey(vo.getVfTypCd())) {
                vo.setVfTypCdNm(feeTypCdMap.get(vo.getVfTypCd()));
            }
		}
	}
	
	
	
	/**
	 * 批量导出分解单
	 *
	 * @param condition
	 * @return
	 * @throws BaseException
	 */
	@Override
	public DataResultVO exportDecomposeList(CapFundVfDtlQueryCondition condition) throws BaseException {
	    if(null == condition){
	        condition = new CapFundVfDtlQueryCondition();
        }
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
        condition.setFlServiceSysCd(CurrentThreadContext.getFlServiceSysCd());
        try {
            DataResultDTO resultDTO=this.capFundVfDtlApiService.exportDecomposeList(condition);
            if(null==resultDTO){
                return new DataResultVO(BaseConstant.IS_YESNO_NO,"导出失败");
            }else{
                return new DataResultVO(Integer.parseInt(resultDTO.getCode()),resultDTO.getInfo(),resultDTO.getData());
            }
        } catch (BaseException e) {
            BaseLogUtils.error(logger,"exportDecomposeList","批量导出分解单详细失败");
			BaseLogUtils.error(logger, "-", "异常", e);
        } catch (NumberFormatException e) {
            BaseLogUtils.error(logger,"exportDecomposeList","批量导出分解单详细失败");
			BaseLogUtils.error(logger, "-", "异常", e);
        }
        return new DataResultVO(BaseConstant.IS_YESNO_NO,"导出失败");
    }

	    
}
